package net.huashitong.Indicators.service;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.dataBean.IndexDataDTO;
import net.huashitong.until.Until;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static net.huashitong.Indicators.dataBean.StaticIndicators.*;
import static net.huashitong.Indicators.utils.DataFormateUntil.*;
import static net.huashitong.Indicators.utils.DataUtil.formatNumber;
import static net.huashitong.until.Until.deepCopy;

@Service
public class RegionContrastService {

    @Autowired
    private IndexDataService dataService;


    private static Logger log = LoggerFactory.getLogger(IndexDataService.class);

    /**
     * 区域对比数据处理
     *
     * @return
     */
    public Map<String, Object> regionContrastProcess(String codeId,
                                                     String datetime,
                                                     String codeType,
                                                     String areacode,
                                                     String areaType,
                                                     Map<String, String> resMap,
                                                     String codeTypeTemp) {
        List<String> cityNameList;
        if (QJ_JD_NC_SR.equals(codeId) && "J".equals(codeType)) {
            //区级季度农村居民人均可支配收入思明、湖里图上增幅应不显示
            cityNameList = Arrays.asList("海沧区", "集美区", "同安区", "翔安区");
        } else if (QJ_JD_NC_ZC.equals(codeId) && "J".equals(codeType)) {
            //区级季度农村居民人均消费支出思明、湖里图上增幅应不显示
            cityNameList = Arrays.asList("海沧区", "集美区", "同安区", "翔安区");
        } else if (QJ_JD_GDP_ONE.equals(codeId) && "J".equals(codeType)) {
            //区级季度地区生产总值第一产业 图上湖里增幅应不显示
            cityNameList = Arrays.asList("思明区", "海沧区", "集美区", "同安区", "翔安区");
        } else if (QJ_ND_GDP_ONE.equals(codeId) && "N".equals(codeType)) {
            //区级季度地区生产总值第一产业 图上湖里增幅应不显示
            cityNameList = Arrays.asList("思明区", "海沧区", "集美区", "同安区", "翔安区");
        } else {
            cityNameList = Arrays.asList("思明区", "湖里区", "海沧区", "集美区", "同安区", "翔安区");
        }

        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> quanGuoMap = new HashMap<>();
        List<IndexDataDTO> fifteencity = new ArrayList<>();
        if ("J".equals(codeType)) {
            datetime = timeToJiduFormat(datetime);
        }
        if("T".equals(codeTypeTemp)){
            if(datetime.length()==4){
                datetime = datetime + "12";
            }else{
                datetime = datetime.substring(0,4) + "12";
            }
            List<IndexDataDTO> fifteencityTemp = dataService.getCityValues(codeId, datetime, areacode, codeType, areaType);
            for (IndexDataDTO dataDTO : fifteencityTemp) {
                if(StringUtils.isBlank(dataDTO.getDatetime())){
                    break;
                }
                if("12".equals(dataDTO.getDatetime().substring(4,6))){
                    fifteencity.add(dataDTO);
                }
            }
            if(fifteencity.size()==0){
                //如果给的时间没有12月份，则取上一年12月份
                String year = datetime.substring(0,4);
                int yearInt = Integer.parseInt(year);
                fifteencityTemp = dataService.getCityValues(codeId, yearInt-1+"12", areacode, codeType, areaType);
                for (IndexDataDTO dataDTO : fifteencityTemp) {
                    if(StringUtils.isBlank(dataDTO.getDatetime())){
                        break;
                    }
                    if("12".equals(dataDTO.getDatetime().substring(4,6))){
                        fifteencity.add(dataDTO);
                    }
                }
                datetime = yearInt-1+"";
            }else{
                datetime = datetime.substring(0,4);
            }

        }else{
            fifteencity = dataService.getCityValues(codeId, datetime, areacode, codeType, areaType);
        }


        //年度只有期末值，我们把期末值放在当前值的字段。最后我们把当前值字段内的值放到累计值字段来，以便app做展示用
        if ("N".equals(codeType)) {
            for (IndexDataDTO dataDTO : fifteencity) {
                dataDTO.setCumulativeValue(dataDTO.getCurrentValue());
            }
        }
        IndexDataDTO quanshi = null;

        /**
         * 如果所有的累计都为0，则返回-
         */
        if ("J".equals(codeType)) {
            datetime = jiduTimeFormat(datetime);
        }
        quanGuoMap.put("datetime", datetime);
        int rank = 1;
        for (IndexDataDTO city : fifteencity) {
            Map<String, Object> map = new HashMap<>();
            map.put("areaName", city.getAreaName());
            map.put("areaCode", city.getAreaCode());
            if ("J".equals(codeType)) {
                datetime = jiduTimeFormat(datetime);
            }
            String vV = "0";
            String cumulativeValue = StringUtils.isBlank(city.getCumulativeValue()) ? "0" : city.getCumulativeValue();
            if (ObjectUtils.isNotBlank(city)) {
                if (ObjectUtils.isNotBlank(city.getCumulativeValue())) {
                    //区级年度人口常住人口城镇化率
                    if (QJ_ND_RK_ZHL.equals(codeId) && "N".equals(codeType) && "A".equals(areaType)) {
                        log.info("保留两位数");
                        vV = dataFormat2(kexuejishu(cumulativeValue));
                        log.info(vV);
                    } else {
                        vV = formatNumber(2, kexuejishu(cumulativeValue));
                    }

                }
            }
            map.put("datetime", datetime);

//            if ("万元".equals(resMap.get("unitname"))) {
//                map.put("cumulative", StringUtils.isBlank(vV) ? "0" : dataformatUnit(vV));
//                map.put("unit", "亿元");
//            } else if ("万美元".equals(resMap.get("unitname"))) {
//                map.put("cumulative", StringUtils.isBlank(vV) ? "0" : dataformatUnit(vV));
//                map.put("unit", "亿美元");
//            } else if ("千美元".equals(resMap.get("unitname"))) {
//                map.put("cumulative", StringUtils.isBlank(vV) ? "0" : dataformatQianUnit(vV));
//                map.put("unit", "亿美元");
//            } else {
//                map.put("cumulative", StringUtils.isBlank(vV) ? "0" : vV);
//                map.put("unit", resMap.get("unitname"));
//            }

            map.put("cumulative", StringUtils.isBlank(vV) ? "0" : vV);
            map.put("unit", resMap.get("unitname"));

            //区级总量数据均改成亿元单位
            if ("万元".equals(resMap.get("unitname"))) {
                map.put("cumulative", StringUtils.isBlank(vV) ? "0" : dataformatUnit(vV));
                map.put("unit", "亿元");
            }
            //区级年度城镇化率增幅在柱状图上保留2位小数
            if (QJ_ND_RK_ZHL.equals(codeId) && "N".equals(codeType)) {
                map.put("ratio", StringUtils.isBlank(city.getCumulativeRatio()) ? "0" : formatNumber(2, city.getCumulativeRatio()));
            } else {
                map.put("ratio", StringUtils.isBlank(city.getCumulativeRatio()) ? "0" : formatNumber(1, city.getCumulativeRatio()));
            }
            rank++;
            list.add(map);
        }
        List<Map<String, Object>> topList = new ArrayList<>();
        for (String cn : cityNameList) {
            for (Map<String, Object> m : list) {
                if (cn.equals(m.get("areaName"))) {
                    topList.add(m);
                    break;
                }
            }
        }

        List<Map<String, Object>> list1 = new ArrayList<>();
        list1.addAll(topList);
        Collections.sort(list1, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String val1 = (String) o1.get("cumulative");
                Double valDouble1 = Double.parseDouble(val1);
                String val2 = (String) o2.get("cumulative");
                Double valDouble2 = Double.parseDouble(val2);
                if (valDouble1 > valDouble2) {
                    return -1;
                } else if (valDouble1 < valDouble2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        list1 = restRank(list1, "1");

        List<Map<String, Object>> list2 = new ArrayList<>();
        list2.addAll(topList);
        Collections.sort(list2, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String val1 = (String) o1.get("ratio");
                Double valDouble1 = Double.parseDouble(val1);
                String val2 = (String) o2.get("ratio");
                Double valDouble2 = Double.parseDouble(val2);
                if (valDouble1 > valDouble2) {
                    return -1;
                } else if (valDouble1 < valDouble2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        list2 = restRank(list2, "2");
        for (Map<String, Object> city : topList) {
            for (Map<String, Object> m1 : list1) {
                if (city.get("areaName").equals(m1.get("areaName"))) {
                    city.put("rank1", m1.get("rank"));

                } else {
                    continue;
                }
            }
            for (Map<String, Object> m2 : list2) {
                if (city.get("areaName").equals(m2.get("areaName"))) {
                    city.put("rank2", m2.get("rank"));

                } else {
                    continue;
                }
            }
        }
        String flag1 = "1";
        String flag2 = "2";
        for (Map<String, Object> result : topList) {
            if (!"-".equals(result.get("rank1"))) {
                flag1 = "0";
            }
            if (!"-".equals(result.get("rank2"))) {
                flag2 = "0";
            }
        }
        List<String> noshow = new ArrayList<>();
        noshow.add(flag1);
        noshow.add(flag2);
        quanGuoMap.put("noshow", noshow);
        //规模以上的，各区域的累计值不要展示
        if ("A010101".equals(codeId) && "Y".equals(codeType)) {
            for (Map<String, Object> objectMap : topList) {
                objectMap.put("cumulative", "0");
            }
        }
        quanGuoMap.put("resultList", topList);
        return quanGuoMap;
    }

    public String jiduTimeFormat(String datetime) {
        String flag = datetime.substring(4, 5);
        switch (flag) {
            case "A":
                datetime = datetime.substring(0, 4) + "03";
                break;
            case "B":
                datetime = datetime.substring(0, 4) + "06";
                break;
            case "C":
                datetime = datetime.substring(0, 4) + "09";
                break;
            case "D":
                datetime = datetime.substring(0, 4) + "12";
                break;
        }
        return datetime;
    }

    public String timeToJiduFormat(String datetime) {
        if (datetime.length() == 5) {
            return datetime;
        }
        String flag = datetime.substring(4, 6);
        switch (flag) {
            case "03":
                datetime = datetime.substring(0, 4) + "A";
                break;
            case "06":
                datetime = datetime.substring(0, 4) + "B";
                break;
            case "09":
                datetime = datetime.substring(0, 4) + "C";
                break;
            case "12":
                datetime = datetime.substring(0, 4) + "D";
                break;
        }
        return datetime;
    }

    public List<Map<String, Object>> restRank(List<Map<String, Object>> def, String flag) {
        List<Map<String, Object>> abc = deepCopy(def);
        int rank = 1;
        switch (flag) {
            case "1":
                for (int i = 0; i < abc.size(); i++) {
                    if (i == 0) {
                        double currentValue = Double.parseDouble(ObjectUtils.isBlank(abc.get(i).get("cumulative")) ? "0.0" : (String) abc.get(i).get("cumulative"));
                        if (currentValue == 0) {
                            abc.get(i).put("rank", "-");
                        } else {
                            abc.get(i).put("rank", rank);
                            rank++;
                        }
                    } else {
                        double currentValue = Double.parseDouble(ObjectUtils.isBlank(abc.get(i).get("cumulative")) ? "0.0" : (String) abc.get(i).get("cumulative"));
                        double preCurrentValue = Double.parseDouble(ObjectUtils.isBlank(abc.get(i - 1).get("cumulative")) ? "0.0" : (String) abc.get(i - 1).get("cumulative"));
                        if (currentValue == preCurrentValue) {
                            if (currentValue == 0) {
                                abc.get(i).put("rank", "-");
                            } else {
                                abc.get(i).put("rank", abc.get(i - 1).get("rank"));
                                rank++;
                            }
                        } else {
                            if (currentValue == 0) {
                                abc.get(i).put("rank", "-");
                            } else {
                                abc.get(i).put("rank", rank);
                                rank++;
                            }
                        }
                    }
                }
                break;
            case "2":
                for (int i = 0; i < abc.size(); i++) {
                    if (ObjectUtils.isBlank(abc.get(i).get("ratio")) || "0".equals(abc.get(i).get("ratio"))) {
                        abc.get(i).put("rank", "-");
                        continue;
                    }

                    if (i == 0) {
                        double currentValue = Double.parseDouble(ObjectUtils.isBlank(abc.get(i).get("ratio")) ? "0" : (String) abc.get(i).get("ratio"));
                        if (currentValue == 0) {
                            abc.get(i).put("rank", "-");
                        } else {
                            abc.get(i).put("rank", rank);
                            rank++;
                        }
                    } else {
                        double currentValue = Double.parseDouble(ObjectUtils.isBlank(abc.get(i).get("ratio")) ? "0" : (String) abc.get(i).get("ratio"));
                        double preCurrentValue = Double.parseDouble(ObjectUtils.isBlank(abc.get(i - 1).get("ratio")) ? "0" : (String) abc.get(i - 1).get("ratio"));
                        if (currentValue == preCurrentValue) {
                            abc.get(i).put("rank", abc.get(i - 1).get("rank"));
                            rank++;
                        } else {
                            abc.get(i).put("rank", rank);
                            rank++;
                        }
                    }
                }
                break;
        }
        return abc;
    }
}
